package com.mrx.xcitools.utils;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.SneakyThrows;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.SshTransport;
import org.eclipse.jgit.transport.Transport;
import org.eclipse.jgit.transport.ssh.jsch.JschConfigSessionFactory;
import org.eclipse.jgit.transport.ssh.jsch.OpenSshConfig;
import org.eclipse.jgit.util.FS;

import java.io.File;

import static com.mrx.xcitools.constant.FileConstant.BASE_REPO_FILE;
import static com.mrx.xcitools.constant.FileConstant.PRIVATE_KEY;

/**
 * @author Mr.X
 * @since 2024-03-10 下午 4:50:02
 */
public class GitUtils {

    @SneakyThrows
    public static Git cloneRepository(String url, String branch, String dstFile) {
        return Git.cloneRepository()
                .setURI(url)
                .setBranch(branch)
                .setTransportConfigCallback(GitUtils::transportCallback)
                .setDirectory(new File(BASE_REPO_FILE, dstFile))
                .setDepth(1)
                .call();
    }

    public static File getProjectDir(String projectDir) {
        return new File(BASE_REPO_FILE, projectDir);
    }

    public static String getProjectDir(Git git) {
        return git.getRepository().getDirectory().getParent();
    }

    private static void transportCallback(Transport transport) {
        ((SshTransport) transport).setSshSessionFactory(SSHConfigSessionFactory.INSTANCE);
    }

    private static final class SSHConfigSessionFactory extends JschConfigSessionFactory {

        public static final SshSessionFactory INSTANCE = new SSHConfigSessionFactory();

        @Override
        protected void configure(OpenSshConfig.Host host, Session session) {
            // 设置 SSH 客户端在连接远程服务器时不进行严格的主机密钥检查
            session.setConfig("StrictHostKeyChecking", "no");
        }

        @Override
        protected JSch createDefaultJSch(FS fs) throws JSchException {
            JSch jSch = super.createDefaultJSch(fs);
            // 添加私钥文件用于身份验证
            jSch.addIdentity(PRIVATE_KEY);
            return jSch;
        }

    }

}
